package uc108.com.jetpackdemo.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import java.util.Random;

import uc108.com.jetpackdemo.R;
import uc108.com.jetpackdemo.databinding.ActivityUserBinding;
import uc108.com.jetpackdemo.room.DatabaseManager;
import uc108.com.jetpackdemo.room.User;
import uc108.com.jetpackdemo.room.UserDao;
import uc108.com.jetpackdemo.viewmodel.UserViewModel;

public class UserActivity extends AppCompatActivity {
    UserViewModel viewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final ActivityUserBinding activityUserBinding = DataBindingUtil.setContentView(this, R.layout.activity_user);

        viewModel = ViewModelProviders.of(this)
                .get(UserViewModel.class);

        viewModel.getCurrentUser().observe(this,
                new Observer<User>() {
                    @Override
                    public void onChanged(User user) {
                        activityUserBinding.setUser(user);
                    }
                });
        UserDao userDao = DatabaseManager.getAppdatabase(getApplication()).userDao();
        activityUserBinding.setUser(userDao.getAllUser().get(0));


    }

    public void update(View view) {
        UserDao userDao = DatabaseManager.getAppdatabase(getApplication()).userDao();
        User u = userDao.getAllUser().get(0);
        String newName = String.format("一粒沙白%d世",new Random().nextInt(100));
        int newAge = new Random().nextInt(1000);
        u.userName = newName;
        u.age = newAge;
        userDao.update(u);

        User newUser = userDao.getAllUser().get(0);
        viewModel.getCurrentUser().setValue(newUser);
    }
}
